<?php

namespace App\Http\Controllers\Api\V1;

use Illuminate\Validation\ValidationException;
use App\Http\Controllers\Api\V1\Resources\NotificationResource;

class NotificationsController extends Controller
{
	public function types()
	{
		$types = request()->user()->jsonNotificationTypes();
		return response()->json($types);
	}

    public function index()
    {
    	$type = request('type');
    	if (!in_array($type, array_keys(config('site.notifications.types')))) {
    		throw ValidationException::withMessages(['err' => '无效的消息类型']);
	    }
    	$notifications = request()->user()->notifications()
		    ->where('type', config("site.notifications.types.{$type}.notification"))->paginate();

    	return NotificationResource::collection($notifications);
    }

    public function count()
    {
	    $type = request('type');
	    if (!in_array($type, array_keys(config('site.notifications.types')))) {
		    throw ValidationException::withMessages(['err' => '无效的消息类型']);
	    }

	    $count = request()->user()->notifications()
		    ->where('type', config("site.notifications.types.{$type}.notification"))->whereNull('read_at')->count();

    	return response()->json(['unread_count' => $count]);
    }

    public function read($id)
    {
    	if (!$notification = request()->user()->unreadNotifications->firstWhere('id', $id)) {
    		throw ValidationException::withMessages(['err' => '目标消息不存在']);
	    }
	    request()->user()->markOneAsRead($notification);
    	return response(null, 204);
    }

    public function readType()
    {
	    $type = request('type');

	    if (!in_array($type, array_keys(config('site.notifications.types')))) {
		    throw ValidationException::withMessages(['err' => '无效的消息类型']);
	    }
    	request()->user()->markTypeAsRead($type);
    	return response(null, 204);
    }

    public function readAll()
    {
    	request()->user()->markAllAsRead();
    	return response(null, 204);
    }
}
